﻿//---------------------------------------------------------------------
// <copyright file="DialogActionFilter.cs" company="Microsoft">
//      This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//      http://www.codeplex.com/hotpot/license
// </copyright>
//---------------------------------------------------------------------
namespace Hotpot.Filters
{
    using System.Web.Mvc;
    using Hotpot.Extensions;
    using Hotpot.Models;
    using Hotpot.Results;

    /// <summary>
    /// ActionFilter to use a DialogSelectionResult to determine redirect actions.
    /// </summary>
    public class DialogActionFilter : IActionFilter
    {
        #region IActionFilter Members
        /// <summary>
        /// Parse the DialogSelectionResult and redirect to the appropriate place.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Result is DialogSelectionResult)
            {
                DialogSelectionResult dialogSelectionResult = (DialogSelectionResult)filterContext.Result;

                if (filterContext.HttpContext.Request.IsJQueryAjaxRequest())
                {
                    if (dialogSelectionResult.IsCancelled)
                    {
                        filterContext.Result = new JsonResult { Data = new { cancel = 1 } };
                    }
                    else if (dialogSelectionResult.IsClientRedirect)
                    {
                        filterContext.Result = new JsonResult { Data = new AjaxRedirect(dialogSelectionResult.ReturnUrl) };
                    }
                }

                if (!(filterContext.Result is JsonResult))
                {
                    filterContext.Result = new RedirectResult(dialogSelectionResult.ReturnUrl);
                }
            }
        }

        /// <summary>
        /// Called by the MVC framework before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
        }
        #endregion
    }
}
